package com.fantasy.blog.handler;

import com.alibaba.fastjson.JSON;
import com.fantasy.blog.dao.pojo.SysUser;
import com.fantasy.blog.service.LoginService;
import com.fantasy.blog.utils.UserThreadLocal;
import com.fantasy.blog.vo.ErrorCode;
import com.fantasy.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 在执行controller 方法之前执行
         * 1.需要判断接口的请求路径是否为 HandlerMethod
         * 2.判断token是否为空，如果为空，未登录
         * 3.不为空，登录验证 loginService checkToken
         * 4.认证成功放行
         * 后改为SpringSecurity
         */
        if(!(handler instanceof HandlerMethod)){
            //可能是访问RequestResourceHandler 访问静态资源resources的springboot程序
            return true;
        }
        String token = request.getHeader("Authorization");

        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        SysUser sysUser = loginService.checkToken(token);
        if(null == sysUser){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        UserThreadLocal.put(sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //不删除有内存溢出的风险
        UserThreadLocal.remove();
    }
}
